package com.tools.service.license.impl;

import com.tools.service.license.KeyManagementService;
import com.tools.utils.RSAUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * 密钥管理服务实现类
 */
@Service
@Slf4j
public class KeyManagementServiceImpl implements KeyManagementService {


    @Resource
    private RSAUtil rsaUtil;

    // 内存中存储密钥（实际项目中应该从配置文件或密钥库加载）
    private PrivateKey cachedPrivateKey;
    private PublicKey cachedPublicKey;


    @Override
    public Map<String, String> generateKeyPair() throws Exception {
        KeyPair keyPair = rsaUtil.generateKeyPair();

        String privateKeyPem = rsaUtil.privateKeyToPem(keyPair.getPrivate());
        String publicKeyPem = rsaUtil.publicKeyToPem(keyPair.getPublic());

        // 缓存密钥
        this.cachedPrivateKey = keyPair.getPrivate();
        this.cachedPublicKey = keyPair.getPublic();

        Map<String, String> result = new HashMap<>();
        result.put("privateKey", privateKeyPem);
        result.put("publicKey", publicKeyPem);

        log.info("新密钥对生成成功");
        return result;
    }

    @Override
    public void loadPrivateKey(String privateKeyPem) throws Exception {
        this.cachedPrivateKey = rsaUtil.loadPrivateKeyFromPem(privateKeyPem);
        log.info("私钥加载成功");
    }

    @Override
    public void loadPublicKey(String publicKeyPem) throws Exception {
        this.cachedPublicKey = rsaUtil.loadPublicKeyFromPem(publicKeyPem);
        log.info("公钥加载成功");
    }

    @Override
    public PrivateKey getCachedPrivateKey() {
        return cachedPrivateKey;
    }

    @Override
    public PublicKey getCachedPublicKey() {
        return cachedPublicKey;
    }

    @Override
    public boolean isKeysLoaded() {
        return cachedPrivateKey != null && cachedPublicKey != null;
    }
}
